package org.hit.burkun.umls;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.hit.burkun.db.DBHelper;
import org.hit.burkun.entities.Entity;

public class GoUmlsMapper extends BaseMapper {

	// 详细说明请参考
	// http://www.nlm.nih.gov/research/umls/sourcereleasedocs/current/GO/
	// http://www.nlm.nih.gov/archive/20050111/research/umls/archive/2002AA/metab.html#TS
	// sy表同义词EXACT类型的，PT表没有过时的
	private String otherCondition = "SAB='GO' and TTY in ('SY', 'PT', 'MTH_SY', 'MTH_PT')";
	private MapidsUmlsDump mapDbh;
	private Entity.TYPE type = Entity.TYPE.GENE_ONTOLOGY;
	private Set<String> mapped = new HashSet<>();
	private Set<String> allids = new HashSet<>();

	public GoUmlsMapper(DBHelper dbh, String tbName, MapidsUmlsDump toDbh) {
		super(dbh, tbName);
		this.mapDbh = toDbh;
	}

	public GoUmlsMapper(DBHelper dbh, MapidsUmlsDump toDbh) {

		this(dbh, "MRCONSO", toDbh);
	}

	public void quickMap(Collection<String> ids) {
		map(ids, "CUI", "CODE", otherCondition);
	};

	@Override
	protected void map(java.util.Collection<String> ids, String conceptFiled,
			String codeFiled, String otherCondition) {
		allids.addAll(ids);
		super.map(ids, conceptFiled, codeFiled, otherCondition);

	};

	@Override
	public void process(Map<String, Set<String>> data) {
		mapped.addAll(data.keySet());
		mapDbh.saveMappedToDb(type, data);
	}

	public Map<String, String> getAllGoData(DBHelper dbh) {
		dbh.connectionDB();
		String queryStr = "select primary_id, acc from go_term where is_obsolete = 0";
		Collection<String[]> res = dbh.queryData(queryStr, 2);
		Map<String, String> hashMap = new HashMap<String, String>();
		for (String[] line : res) {
			hashMap.put(line[1], line[0]);
		}
		dbh.disconnection();
		return hashMap;
	}

	public Map<String, String> getAllGoData() {
		Map<String, String> res = getAllGoData(this.dbh);
		return res;
	}

	@Override
	public void end() {
		allids.removeAll(mapped);
		mapDbh.saveUnMappedToDb(type, allids);
		super.end();
	}

	public static void main(String[] args) {
		DBHelper dbh =  DBHelper.getServerData();
		MapidsUmlsDump mapDbh = new MapidsUmlsDump(
				 DBHelper.getServerData(), "map_umls_ids");
		GoUmlsMapper mapper = new GoUmlsMapper(dbh, mapDbh);
		mapper.begin();
		Map<String, String> data = mapper.getAllGoData( DBHelper.getServerData());
		mapper.quickMap(data.keySet());
		mapper.end();
	}

}
